<template>
  <el-dialog v-model="visible" title="选择源单" width="80%">
    <el-table
      :data="props.sourceDocList"
      style="width: 100%"
      border
      draggable
      @row-click="handleRowClick"
      @selection-change="handleSelectionChange"
      :header-cell-style="{ 'background-color': '#f5f7fa' }"
      ref="sourceDocTable"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="50" />
      <el-table-column prop="docNo" label="源单编号" min-width="130" />
      <el-table-column prop="businessType" label="业务类别" min-width="100" />
      <el-table-column prop="docDate" label="单据日期" min-width="110" />
      <el-table-column prop="slipPrice" label="单据金额" min-width="100" align="right" />
      <el-table-column prop="unwrittenOffAmount" label="未核销金额" min-width="120" align="right" />
    </el-table>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="confirmSelection">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, defineExpose } from 'vue';

const props = defineProps({
  sourceDocList: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['confirm']);
const visible = ref(false);
const selectedDocs = ref([]);
const sourceDocTable = ref(null);

const open = () => {
  visible.value = true;
  selectedDocs.value = [];
};

const handleRowClick = (row, column, event) => {
  // 如果点击的是复选框本身，则不处理（避免重复触发）
  if (event.target.classList.contains('el-checkbox__inner')) {
    return;
  }
  
  // 切换当前行的选择状态
  sourceDocTable.value.toggleRowSelection(row);
  
  // 更新选中的文档列表
  selectedDocs.value = sourceDocTable.value.getSelectionRows();
};

const handleSelectionChange = (selection) => {
  selectedDocs.value = selection;
};

const confirmSelection = () => {
  if (selectedDocs.value.length > 0) {
    emit('confirm', selectedDocs.value);
    visible.value = false;
  }
};

defineExpose({ open });
</script>

<style scoped>
/* 确保复选框可独立点击 */
:deep(.el-table__row) {
  cursor: pointer;
}

/* 复选框区域不阻止事件 */
:deep(.el-checkbox__inner) {
  pointer-events: auto !important;
}
</style>